<?php

namespace App\Http\Controllers\Home;


use App\Model\Area;
use App\Model\Checkentry;
use App\Model\Comcheckagain;
use App\Model\Comcheckagaindetail;
use App\Model\Producelist;
use App\User;
use Illuminate\Support\Facades\Auth;
use PhpOffice\PhpWord\TemplateProcessor;

use App\Http\Controllers\Controller;

use App\Model\Checkgroup;
use App\Model\Checknegative;
use App\Model\Checkaccord;
use App\Model\Checkcommand;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comcheckdetail;

use Illuminate\Http\Request;
use App\Http\Requests\CheckRequest;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use Maatwebsite\Excel\Excel;
use Illuminate\Support\Facades\DB;
use PDO;
class ComcheckController extends Controller
{

    public function choose($id) {
        $company = Company::find($id)->getGroup()->first();
//        $entryIds = $company->entryIds;
        $groupId = $company->id;
//        dd($groupId);
        $comcheck = Comcheck::where(['companyId'=>$id,'groupId'=>$groupId])->select('id','wordsUrl')->first();
        $productCheck = Comcheck::where(['companyId'=>$id,'status'=>2])->select('id')->first();
        $checkId = 0;
        $productCheckId = 0;
        if($comcheck){
            $checkId = $comcheck->id;
        }
        if($productCheck) {
            $productCheckId = $productCheck->id;
        }
        $checkgroup = new Checkgroup();
//        $entry = $checkgroup->getEntry($entryIds);
        return view('check/choose')
//            ->with('entry',$entry)
            ->with('wordsUrl',$comcheck['wordsUrl'])
            ->with('checkId',$checkId)
            ->with('productCheckId',$productCheckId)
            ->with('id',$id);
    }
    public function show($id,$groupId = '') {
//        dd('sd');
        if($groupId) {
            $group = Checkgroup::where('id',$groupId)->first();
            $entryIds = $group->entryIds;
        } else {
            $group = Company::find($id)->getGroup()->first();
            $entryIds = $group->entryIds;
            $groupId = $group->id;
        }
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $comcheck = Comcheck::where(['companyId'=>$id,'groupId'=>$groupId])->first();
        if($comcheck){
            return redirect('check/choose/'.$id);
        }
        return view('check/show')
            ->with('entrys',$entrys)
            ->with('groupId',$groupId)
            ->with('id',$id);
    }
    public function produceShow($id){
        $data = Checkgroup::all();
        $entry = Checkentry::select(DB::raw('id,entry,groupId'))
            ->where('groupId','!=','null')
            ->orderBy('groupId', 'asc')
            ->get();
        $entrydata = [];
//        foreach ($entry as $v){
//            if (!in_array($v['groupId'],$entrydata)){
//                $entrydata[$v['groupId']][] = $v;
//
//            }else{
//                array_push($entrydata[$v['groupId']],$v);
//            }
//        }
        $indexdata = [];
        foreach ($data as $k=>$v){
            $first = self::getFirstChar($v->name);
            if (!in_array($first,$indexdata)){
                $indexdata[$first][] = $v;
            }else{
                array_push($indexdata[$first],$v);
            }
        }
        ksort($indexdata);
        return view('check/produce_show',[
            'data'=>$data,
            'entrydata'=>$entrydata,
            'indexdata'=>$indexdata,
            'id'=>$id,
        ]);
    }

    public function groupSearch(Request $quest ,$id)
    {
        $keyword = $quest->input('keyword');
        $data = Checkgroup::all();

        if(empty($keyword)) {
            \Session::flash('error', '输入信息有误!');
            return back();
        }
        $search = Checkgroup::where('name','like','%'.$keyword.'%')->get();

        if($keyword) {
            foreach($search as $k => $v) {
                $search[$k]->name = preg_replace("/($keyword)/i",
                    "<font color=red><b>\\1</b></font>",
                    $v->name);
            }
        }
        return view('check/groupsearch',[
            'search'=>$search,
            'data'=>$data,
            'id'=>$id,
        ]);

    }
    public function highSearch($id){
        $data  = Producelist::where('parent_id','=',0)->get(['id','produce_name','type']);
        return view('check/high_search',[
            'data'=>$data,
            'id'=>$id,
        ]);
    }
    public function getProduce(Request $request,$pid)
    {
        $data = Producelist::where('parent_id',$pid)->get();
        echo json_encode($data);
    }
    public function show1($id,$groupId = '') {
        if($groupId) {
            $group = Checkgroup::where('id',$groupId)->first();
            $entryIds = $group->entryIds;
        } else {
            $group = Company::find($id)->getGroup()->first();
            $entryIds = $group->entryIds;
            $groupId = $group->id;
        }

        $checkgroup = new Checkgroup();
        $entrys = $checkgroup->getEntry($entryIds);
        return view('check/show')
            ->with('entrys',$entrys)
            ->with('groupId',$groupId)
            ->with('id',$id);
    }



    public function create(CheckRequest $request) {
        $data = $request->all();
        $check['companyId'] = $data['id'];
        $user = Auth::user();
        $check['userId'] = $user->id;
        $check['created'] = date('Y-m-d H:i:s',time());
        $check['groupId'] = $data['groupId'];
        $groupinfo = Checkgroup::find($data['groupId']);
        $status = $groupinfo->status;
        $check['status'] = $status;
        $comcheck = Comcheck::where(['companyId'=>$check['companyId'],'groupId'=>$check['groupId']])->first();
        if($comcheck){
            return redirect('check/choose/'.$check['companyId']);
        }
        // $checkId = 1;
        $checkId = Comcheck::insertGetId($check);
        $entryIds = $data['entryId'];
        $statuses = $data['status'];
        $contents = $data['content'];
        $pictures = empty($data['picture'])?0:$data['picture'];
        $negatives = empty($data['negative'])?0:$data['negative'];
        foreach ($entryIds as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
//            $checkdetail[$k]['userId'] = $user->id;
            $checkdetail[$k]['entryId'] = $v;
            $checkdetail[$k]['pictures'] = '';
        }
        foreach ($statuses as $k => $v) {
            $checkdetail[$k]['status'] = $v;
        }
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['content'] = $v;
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                $checkdetail[$k]['pictures'] = $v;
            }
        }

        foreach ($checkdetail as $k => $v) {
            $checkdetail[$k]['negatives'] = '';
            if($negatives) {
                foreach ($negatives as $kk => $vv) {
                    if($v['entryId'] == $kk){
                        $checkdetail[$k]['negatives'] = $vv;
                    }
                }
            }

        }
        $comCheckdetail = new Comcheckdetail();
        $comCheckdetail->addAll($checkdetail);
        // $this->exportWord1($checkId);
        return redirect('check/inconform/'.$checkId);
    }


    public function inconform($id)
    {

        $detail = new Comcheckdetail();
        $comcheck = Comcheck::find($id);
        $infos = $detail->getInconform($id);
        return view('check/inconform')
            ->with('companyId',$comcheck->companyId)
            ->with('id',$id)
            ->with('infos',$infos);
    }

    public function del($id)
    {
        $detail = Comcheckdetail::find($id);
        $checkId = $detail->checkId;
        $detail->status = '1';
        $detail->save();
        return redirect('check/inconform/'.$checkId);
    }

    public function signature(Request $request)
    {
        $id = $request->input('id');
        $comcheck = Comcheck::find($id);
        $imgbase=$request->input('imgbase');
        if(!$imgbase) {
            return redirect('check/inconform/'.$id);
        }
        $base64_str = substr($imgbase, strpos($imgbase, ",")+1);
        $image=base64_decode($base64_str);
        $imgname=rand(1000,10000).time().'.png';
        $path = 'images/'.date('Ymd').'/'.$imgname;
        Storage::put($path,$image);
        Comcheck::where('id','=',$id)->update(['comsignature'=>'/storage/'.$path]);
        return redirect('check/choose/'.$comcheck['companyId']);
    }
    /**
     * 生成第一个检测报告
     *
     **/
    protected function exportWord1($companyId)
    {
        $company = Company::find($companyId);
        $comcheck = new Comcheck();
        $checkinfo = $comcheck->where(['companyId'=>$companyId,'status'=>1])->first();
        if(!$checkinfo) {
            return redirect('/check/choose/'.$companyId);
        }
        // if($checkinfo->wordsUrl) {
        //     return redirect('/check/choose/'.$companyId);
        // }
        $created = date('Y-m-d',strtotime($checkinfo->created));
        $year = date('Y',strtotime($checkinfo->created));
        $month = date('m',strtotime($checkinfo->created));
        $day = date('d',strtotime($checkinfo->created));
        // $company = Comcheck::find($id)->getCompany()->first();
        //负面清单
        $standardNegative = $comcheck->getStandardNegative($companyId);
        $productNegative = $comcheck->getProductNegative($companyId);
        $src = public_path().$checkinfo['signature'];
        $templateProcessor =  new TemplateProcessor('./word/word1.docx');

        $comName = $company->comName;
        $data['comName'] = $comName;
        $data['address'] = $company->address;
        $data['year'] = $year;
        $data['month'] = $month;
        $data['day'] = $day;
        $data['archives'] = '';
        $data['danger'] = '';
        $i = 0;
        $j = 0;
        foreach($standardNegative as $k => $v)
        {
            $i++;
            $data['archives'] .= '('.$i.')'.$v['content'].'<w:br />';
        }
        foreach ($productNegative as $k => $v) {
            $j++;
            $data['danger'] .= '('.$j.')'.$v['content'].'<w:br />';
        }
        // $templateProcessor->setValue('comName','青科安全');
        foreach($data as $k=>$v){
            $templateProcessor->setValue($k,$v);
        }
        $templateProcessor->setImageValue('image','.'.$checkinfo['comsignature']);
        $docName = $comName.'检测报告1_' . $created;
        $wordUrl = './word/'.$docName.'.docx';
        $templateProcessor->saveAs($wordUrl);
        $checkinfo->wordsUrl = $wordUrl;
        $checkinfo->save();
        return redirect('check/choose/'.$companyId);
        // return redirect($wordUrl);
        // return response()->download($wordUrl);
    }


    public function getChecknegative($id) {
        header("Access-Control-Allow-Origin: *");
        $checknegative = Checknegative::where('entryId',$id)->get();
        return response()->json($checknegative)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function getCheckaccord($id) {
        header("Access-Control-Allow-Origin: *");
        $checkaccord = Checkaccord::where('entryId',$id)->get();
        $checkcommand = Checkcommand::where('entryId',$id)->get();
        
        $data['checkaccord'] = json_decode(preg_replace("/(处罚：)/i", 
        "<font color=red><b>\\1</b></font>", 
        json_encode($checkaccord,JSON_UNESCAPED_UNICODE)));
        $data['checkcommand'] = $checkcommand;
        return response()->json($data)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function zhili() {
        return view('check/zhili');
    }
    public function taizhang() {
        return view('check/taizhang');
    }
    public static function getFirstChar($str) {
        if (empty($str)) {
            return '';
        }

        $fir = $fchar = ord($str[0]);
        if ($fchar >= ord('A') && $fchar <= ord('z')) {
            return strtoupper($str[0]);
        }

        $s1 = @iconv('UTF-8', 'gb2312', $str);
        $s2 = @iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        if (!isset($s[0]) || !isset($s[1])) {
            return '';
        }

        $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

        if (is_numeric($str)) {
            return $str;
        }

        if (($asc >= -20319 && $asc <= -20284) || $fir == 'A') {
            return 'A';
        }
        if (($asc >= -20283 && $asc <= -19776) || $fir == 'B') {
            return 'B';
        }
        if (($asc >= -19775 && $asc <= -19219) || $fir == 'C') {
            return 'C';
        }
        if (($asc >= -19218 && $asc <= -18711) || $fir == 'D') {
            return 'D';
        }
        if (($asc >= -18710 && $asc <= -18527) || $fir == 'E') {
            return 'E';
        }
        if (($asc >= -18526 && $asc <= -18240) || $fir == 'F') {
            return 'F';
        }
        if (($asc >= -18239 && $asc <= -17923) || $fir == 'G') {
            return 'G';
        }
        if (($asc >= -17922 && $asc <= -17418) || $fir == 'H') {
            return 'H';
        }
        if (($asc >= -17417 && $asc <= -16475) || $fir == 'J') {
            return 'J';
        }
        if (($asc >= -16474 && $asc <= -16213) || $fir == 'K') {
            return 'K';
        }
        if (($asc >= -16212 && $asc <= -15641) || $fir == 'L') {
            return 'L';
        }
        if (($asc >= -15640 && $asc <= -15166) || $fir == 'M') {
            return 'M';
        }
        if (($asc >= -15165 && $asc <= -14923) || $fir == 'N') {
            return 'N';
        }
        if (($asc >= -14922 && $asc <= -14915) || $fir == 'O') {
            return 'O';
        }
        if (($asc >= -14914 && $asc <= -14631) || $fir == 'P') {
            return 'P';
        }
        if (($asc >= -14630 && $asc <= -14150) || $fir == 'Q') {
            return 'Q';
        }
        if (($asc >= -14149 && $asc <= -14091) || $fir == 'R') {
            return 'R';
        }
        if (($asc >= -14090 && $asc <= -13319) || $fir == 'S') {
            return 'S';
        }
        if (($asc >= -13318 && $asc <= -12839) || $fir == 'T') {
            return 'T';
        }
        if (($asc >= -12838 && $asc <= -12557) || $fir == 'W') {
            return 'W';
        }
        if (($asc >= -12556 && $asc <= -11848) || $fir == 'X') {
            return 'X';
        }
        if (($asc >= -11847 && $asc <= -11056) || $fir == 'Y') {
            return 'Y';
        }
        if (($asc >= -11055 && $asc <= -10247) || $fir == 'Z') {
            return 'Z';
        }

        return '';
    }


}
